package com.irdstudio.efp.batch.service.impl.psd;

import com.alibaba.fastjson.JSONObject;
import com.irdstudio.basic.framework.core.constant.BaseConstant;
import com.irdstudio.basic.framework.core.util.DateTool;
import com.irdstudio.basic.framework.core.util.StringUtil;
import com.irdstudio.basic.framework.core.util.TimeUtil;
import com.irdstudio.basic.sequence.service.facade.SequenceService;
import com.irdstudio.efp.batch.service.facade.psd.PsdRiskWarningDealRiskService;
import com.irdstudio.efp.console.common.ConsoleConstant;
import com.irdstudio.efp.limit.service.facade.LmtPrdContService;
import com.irdstudio.efp.limit.service.vo.LmtPrdContVO;
import com.irdstudio.efp.nls.common.constant.sed.SedNlsEnum;
import com.irdstudio.efp.riskm.service.facade.LmtFreezeAppService;
import com.irdstudio.efp.riskm.service.facade.LmtTerminateAppService;
import com.irdstudio.efp.riskm.service.facade.PsdRscWarnLoanTempHisService;
import com.irdstudio.efp.riskm.service.facade.RscWarnLoanService;
import com.irdstudio.efp.riskm.service.vo.LmtFreezeAppVO;
import com.irdstudio.efp.riskm.service.vo.LmtTerminateAppVO;
import com.irdstudio.efp.riskm.service.vo.PsdRscWarnLoanTempHisVo;
import com.irdstudio.efp.riskm.service.vo.RscWarnLoanVO;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.stereotype.Service;

import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.util.ArrayList;
import java.util.List;
import java.util.Objects;
import java.util.Optional;

@Service("psdRiskWarningDealRiskService")
public class PsdRiskWarningDealRiskServiceImpl implements PsdRiskWarningDealRiskService {

    private static Logger logger = LoggerFactory.getLogger(PsdRiskWarningDealRiskServiceImpl.class);

    @Autowired
    @Qualifier("rscWarnLoanService")
    private RscWarnLoanService rscWarnLoanService;
    @Autowired
    @Qualifier("lmtPrdContService")
    private LmtPrdContService lmtPrdContService;
    @Autowired
    private SequenceService sequenceService;
    @Autowired
    @Qualifier("lmtFreezeAppService")
    private LmtFreezeAppService lmtFreezeAppService;
    @Autowired
    @Qualifier("lmtTerminateAppService")
    private LmtTerminateAppService lmtTerminateAppService;
    @Autowired
    private PsdRscWarnLoanTempHisService psdRscWarnLoanTempHisService;

    @Override
    public Boolean dealPsdRiskWarning() throws Exception {
        logger.info("普税贷风险预警冻结终止任务处理开始...");
        // 分页大小
        Integer pageSize = 1000;
        // 分页信息
        RscWarnLoanVO pageInfo = new RscWarnLoanVO();
        // 页数
        int page = 1;
        // pageSize初始化
        pageInfo.setSize(pageSize);
        // 判断循环次数
        try{
            int size = rscWarnLoanService.queryByDealFlagCount();
            String size_msg = "【查询普税贷风险预警信息数据量】：" + size;
            logger.info(size_msg, "message{}");
            int loopCount = (size / pageInfo.getSize()) + (size % pageInfo.getSize() == 0 ? 0 : 1);
            for (int i = 0; i < loopCount; i++) {
                String page_msg = "【普税贷风险预警信息查询】当前页数：" + pageInfo.getPage() + "，分页大小：" + pageInfo.getSize();
                logger.info(page_msg, "message{}");
                // 分页查询普税贷风险预警信息，发送预警信息
                processDealRiskWarningMsg(Optional.ofNullable(rscWarnLoanService.queryByDealFlagByPage(pageInfo)).orElseGet(ArrayList::new));
                // 下一页
                pageInfo.setPage(++page);
            }
            logger.info("普税贷风险预警冻结终止任务处理结束...");
        }catch (Exception e){
            e.printStackTrace();
        }
        return true;
    }

    private void processDealRiskWarningMsg(List<RscWarnLoanVO> warnList){
        if (Objects.isNull(warnList) || warnList.isEmpty()) {
            logger.info("普税贷风险预警信息查询为空！");
            return;
        }
        for (RscWarnLoanVO r : warnList) {
            if (StringUtil.isNullorBank(r.getCertCode())) {
                continue;
            }
            if (SedNlsEnum.YesOrNo.NO.getValue().equals(r.getDealFlag()) && !StringUtil.isNullorBank(r.getCusName()) && !StringUtil.isNullorBank(r.getRiskLevel())) {
                boolean dealFlag = false;
                if (r.getRiskLevel().equals("01")){
                    dealFlag = terminalBill(r);
                }else if (r.getRiskLevel().equals("02")){
                    dealFlag = freezeBill(r);
                }else if(r.getRiskLevel().equals("03")){
                    dealFlag = terminalBillByL3(r);
                }
                if (dealFlag) {
                    // 风险预警台账信息
                    RscWarnLoanVO inRscWarnLoanVo = new RscWarnLoanVO();
                    // 借据号
                    inRscWarnLoanVo.setCertCode(r.getCertCode());
                    // 风险处理标识
                    inRscWarnLoanVo.setDealFlag(SedNlsEnum.YesOrNo.YES.getValue());
                    // 最后更新人
                    inRscWarnLoanVo.setLastUpdateUser(BaseConstant.ADMIN);
                    // 最后更新时间
                    inRscWarnLoanVo.setLastUpdateTime(DateTool.getCurrentDateTime());
                    int num = rscWarnLoanService.updateDealFlagByBillNo(inRscWarnLoanVo);
                    if (num == -1) {
                        logger.error("普税贷风险预警处理失败，更新风险预警信息失败！{}", JSONObject.toJSONString(inRscWarnLoanVo));
                    }
                }
            }
        }
    }

    private boolean freezeBill(RscWarnLoanVO rscWarnLoanVO){
        LmtPrdContVO lmtPrdContVO = getLmtPrdContInfo(rscWarnLoanVO);
        LmtFreezeAppVO lmtFreezeAppVO = new LmtFreezeAppVO();
        if (Objects.isNull(lmtPrdContVO)){
            return false;
        }
        lmtFreezeAppVO.setLmtContNo(lmtPrdContVO.getLmtContNo());
        lmtFreezeAppVO.setLmtAmt(lmtPrdContVO.getLmtAmt());
        lmtFreezeAppVO.setAvailAmt(lmtPrdContVO.getAvailAmt());
        lmtFreezeAppVO.setCyclicFlg(lmtPrdContVO.getCyclicFlg());
        lmtFreezeAppVO.setChannelNo(lmtPrdContVO.getChannelNo());
        lmtFreezeAppVO.setPrdId(lmtPrdContVO.getPrdId());
        lmtFreezeAppVO.setPrdCode(lmtPrdContVO.getPrdCode());
        lmtFreezeAppVO.setPrdName(lmtPrdContVO.getPrdName());
        lmtFreezeAppVO.setCertType(lmtPrdContVO.getCertType());
        lmtFreezeAppVO.setCusId(lmtPrdContVO.getCusId());
        lmtFreezeAppVO.setOrgCode(lmtPrdContVO.getLegalOrgCode());
        lmtFreezeAppVO.setCusName(rscWarnLoanVO.getCusName());
        lmtFreezeAppVO.setCertCode(rscWarnLoanVO.getCertCode());
        lmtFreezeAppVO.setStartDate(rscWarnLoanVO.getLoanStartDate());
        lmtFreezeAppVO.setExpireDate(rscWarnLoanVO.getLoanEndDate());
        lmtFreezeAppVO.setCreateUser("admin");
        lmtFreezeAppVO.setCreateTime(TimeUtil.getCurrentDateTime());
        lmtFreezeAppVO.setLastUpdateUser("admin");
        lmtFreezeAppVO.setLastUpdateTime(TimeUtil.getCurrentDateTime());
        lmtFreezeAppVO.setApplyDate(TimeUtil.getCurDate());
        lmtFreezeAppVO.setApproveStatus(ConsoleConstant.APRV_STATUS_03);
        lmtFreezeAppVO.setAprvUserName("系统管理员");
        lmtFreezeAppVO.setAprvUserCode("admin");
        lmtFreezeAppVO.setAprvDate(TimeUtil.getCurrentDate());
        lmtFreezeAppVO.setAprvComment("触发二级预警，自动冻结");
        lmtFreezeAppVO.setFrzReason("普税贷产品客户" + rscWarnLoanVO.getCusName() + "触发二级预警，系统自动冻结！");
        lmtFreezeAppVO.setCusManager(rscWarnLoanVO.getCusManager());
        try {
            lmtFreezeAppVO.setFrzSerno(sequenceService.getSequence("FRZ_SERNO", "null", "null"));
        } catch (Exception e) {
            e.printStackTrace();
        }
        int out = lmtFreezeAppService.insertLmtFreezeApp(lmtFreezeAppVO);
        lmtPrdContVO.setLmtStatus(ConsoleConstant.LIMIT_STS_00);
        lmtPrdContVO.setLastUpdateTime(TimeUtil.getCurrentDateTime());
        lmtPrdContVO.setLastUpdateUser("admin");
        int out2 = lmtPrdContService.updateByPk(lmtPrdContVO);
        if (out==1 && out2==1){
            return true;
        }
        return false;
    }

    private boolean terminalBill(RscWarnLoanVO rscWarnLoanVO){
        LmtPrdContVO lmtPrdContVO = getLmtPrdContInfo(rscWarnLoanVO);
        LmtTerminateAppVO lmtTerminateAppVO = new LmtTerminateAppVO();
        if (Objects.isNull(lmtPrdContVO)){
            return false;
        }
        lmtTerminateAppVO.setLmtContNo(lmtPrdContVO.getLmtContNo());
        lmtTerminateAppVO.setLmtAmt(lmtPrdContVO.getLmtAmt());
        lmtTerminateAppVO.setAvailAmt(lmtPrdContVO.getAvailAmt());
        lmtTerminateAppVO.setCyclicFlg(lmtPrdContVO.getCyclicFlg());
        lmtTerminateAppVO.setChannelNo(lmtPrdContVO.getChannelNo());
        lmtTerminateAppVO.setPrdId(lmtPrdContVO.getPrdId());
        lmtTerminateAppVO.setPrdCode(lmtPrdContVO.getPrdCode());
        lmtTerminateAppVO.setPrdName(lmtPrdContVO.getPrdName());
        lmtTerminateAppVO.setCertType(lmtPrdContVO.getCertType());
        lmtTerminateAppVO.setCusId(lmtPrdContVO.getCusId());
        lmtTerminateAppVO.setOrgCode(lmtPrdContVO.getLegalOrgCode());
        lmtTerminateAppVO.setCusName(rscWarnLoanVO.getCusName());
        lmtTerminateAppVO.setCertCode(rscWarnLoanVO.getCertCode());
        lmtTerminateAppVO.setCreateUser("admin");
        lmtTerminateAppVO.setCreateTime(TimeUtil.getCurrentDateTime());
        lmtTerminateAppVO.setLastUpdateUser("admin");
        lmtTerminateAppVO.setLastUpdateTime(TimeUtil.getCurrentDateTime());
        lmtTerminateAppVO.setApplyDate(TimeUtil.getCurDate());
        lmtTerminateAppVO.setApproveStatus(ConsoleConstant.APRV_STATUS_03);
        lmtTerminateAppVO.setAprvUserName("系统管理员");
        lmtTerminateAppVO.setAprvUserCode("admin");
        lmtTerminateAppVO.setAprvDate(TimeUtil.getCurrentDate());
        lmtTerminateAppVO.setAprvComment("触发一级预警，自动终止");
        lmtTerminateAppVO.setTerminateReason("普税贷产品客户" + rscWarnLoanVO.getCusName() + "触发一级预警，系统自动终止！");
        lmtTerminateAppVO.setCusManager(rscWarnLoanVO.getCusManager());
        try {
            lmtTerminateAppVO.setTerminateSerno(sequenceService.getSequence("T_SERNO","null","null"));
        } catch (Exception e) {
            e.printStackTrace();
        }
        int out = lmtTerminateAppService.insertLmtTerminateApp(lmtTerminateAppVO);
        lmtPrdContVO.setLmtStatus(ConsoleConstant.LIMIT_STS_03);
        lmtPrdContVO.setLastUpdateTime(TimeUtil.getCurrentDateTime());
        lmtPrdContVO.setLastUpdateUser("admin");
        int out2 = lmtPrdContService.updateByPk(lmtPrdContVO);
        if (out==1 && out2==1){
            return true;
        }
        return false;
    }

    private boolean terminalBillByL3(RscWarnLoanVO rscWarnLoanVO){
        LmtPrdContVO lmtPrdContVO = getLmtPrdContInfo(rscWarnLoanVO);
        LmtTerminateAppVO lmtTerminateAppVO = new LmtTerminateAppVO();
        if (Objects.isNull(lmtPrdContVO)){
            return false;
        }
        lmtTerminateAppVO.setLmtContNo(lmtPrdContVO.getLmtContNo());
        lmtTerminateAppVO.setLmtAmt(lmtPrdContVO.getLmtAmt());
        lmtTerminateAppVO.setAvailAmt(lmtPrdContVO.getAvailAmt());
        lmtTerminateAppVO.setCyclicFlg(lmtPrdContVO.getCyclicFlg());
        lmtTerminateAppVO.setChannelNo(lmtPrdContVO.getChannelNo());
        lmtTerminateAppVO.setPrdId(lmtPrdContVO.getPrdId());
        lmtTerminateAppVO.setPrdCode(lmtPrdContVO.getPrdCode());
        lmtTerminateAppVO.setPrdName(lmtPrdContVO.getPrdName());
        lmtTerminateAppVO.setCertType(lmtPrdContVO.getCertType());
        lmtTerminateAppVO.setCusId(lmtPrdContVO.getCusId());
        lmtTerminateAppVO.setOrgCode(lmtPrdContVO.getLegalOrgCode());
        lmtTerminateAppVO.setCusName(rscWarnLoanVO.getCusName());
        lmtTerminateAppVO.setCertCode(rscWarnLoanVO.getCertCode());
        lmtTerminateAppVO.setCreateUser("admin");
        lmtTerminateAppVO.setCreateTime(TimeUtil.getCurrentDateTime());
        lmtTerminateAppVO.setLastUpdateUser("admin");
        lmtTerminateAppVO.setLastUpdateTime(TimeUtil.getCurrentDateTime());
        lmtTerminateAppVO.setApplyDate(TimeUtil.getCurDate());
        lmtTerminateAppVO.setApproveStatus(ConsoleConstant.APRV_STATUS_03);
        lmtTerminateAppVO.setAprvUserName("系统管理员");
        lmtTerminateAppVO.setAprvUserCode("admin");
        lmtTerminateAppVO.setAprvDate(TimeUtil.getCurrentDate());
        lmtTerminateAppVO.setAprvComment("连续2个月触发关注级别预警，自动终止");
        lmtTerminateAppVO.setTerminateReason("普税贷产品客户" + rscWarnLoanVO.getCusName() + "连续2个月触发关注级别预警，系统自动终止！");
        lmtTerminateAppVO.setCusManager(rscWarnLoanVO.getCusManager());
        try {
            lmtTerminateAppVO.setTerminateSerno(sequenceService.getSequence("T_SERNO","null","null"));
        } catch (Exception e) {
            e.printStackTrace();
        }
        int out = lmtTerminateAppService.insertLmtTerminateApp(lmtTerminateAppVO);
        lmtPrdContVO.setLmtStatus(ConsoleConstant.LIMIT_STS_03);
        lmtPrdContVO.setLastUpdateTime(TimeUtil.getCurrentDateTime());
        lmtPrdContVO.setLastUpdateUser("admin");
        int out2 = lmtPrdContService.updateByPk(lmtPrdContVO);
        if (out==1 && out2==1){
            return true;
        }
        return false;
    }

    private LmtPrdContVO getLmtPrdContInfo(RscWarnLoanVO rscWarnLoanVO){
        LmtPrdContVO lmtPrdContVO = new LmtPrdContVO();
        lmtPrdContVO.setCertCode(rscWarnLoanVO.getCertCode());
        lmtPrdContVO.setPrdId("11110003");
        lmtPrdContVO.setPrdCode("11110003");
        lmtPrdContVO.setLmtStatus("02");
        List<LmtPrdContVO> list = lmtPrdContService.queryLmtPrdList(lmtPrdContVO);
        if (Objects.nonNull(list) && list.size()==1){
            return list.get(0);
        }
        return null;
    }



}
